package leetcode_链表;

import general_class.ListNode;

/**
 * 环形链表 II
 * 算法：快慢指针
 *
 * @author yezh
 * @date 2024/1/10 16:32
 */
public class _142 {

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) return null;
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                fast = head;
                while (slow != fast) {
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
        return null;
    }

}
